<!--
  -    Copyright (c) 2018-2025, cloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: cloud
  -->

<template>
  <div class="app-container calendar-list-container">
    <BasicContainer>
      <ElRow>
        <ElForm ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
          <ElCol :span="12">
            <div class="grid-content bg-purple">
              <ElFormItem label="头像">
                <ElUpload
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  class="avatar-uploader"
                  action="/admin/sys-file/upload">
                  <img v-if="ruleForm.avatar" :src="avatarUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </ElUpload>
              </ElFormItem>
              <ElFormItem label="用户名" prop="username">
                <ElInput v-model="ruleForm.username" type="text" disabled />
              </ElFormItem>
              <ElFormItem label="手机号" prop="phone">
                <ElInput v-model="ruleForm.phone" placeholder="验证码登录使用" />
              </ElFormItem>
              <ElFormItem label="昵称" prop="nickname">
                <ElInput v-model="ruleForm.nickname" placeholder="昵称" />
              </ElFormItem>
              <ElFormItem label="姓名" prop="name">
                <ElInput v-model="ruleForm.name" placeholder="姓名" />
              </ElFormItem>
              <ElFormItem label="邮箱" prop="email">
                <ElInput v-model="ruleForm.email" placeholder="邮箱" />
              </ElFormItem>
              <ElFormItem label="社交登录" prop="social">
                <a href="#" class="icon-weixin" @click="handleClick('wechat')"></a>｜
                <a href="#" class="icon-qq" @click="handleClick('tencent')"></a> |
                <a href="#" class="icon-gitee-fill-round" @click="handleClick('gitee')"></a> |
                <a href="#" class="icon-C" @click="handleClick('osc')"></a>
              </ElFormItem>
              <ElFormItem label="原密码" prop="password">
                <ElInput v-model="ruleForm.password" type="password" auto-complete="off" />
              </ElFormItem>
              <ElFormItem label="新密码" prop="newpassword1">
                <ElInput v-model="ruleForm.newpassword1" type="password" auto-complete="off" />
              </ElFormItem>
              <ElFormItem label="确认密码" prop="newpassword2">
                <ElInput v-model="ruleForm.newpassword2" type="password" auto-complete="off" />
              </ElFormItem>
              <ElFormItem>
                <ElButton type="primary" @click="submitForm()">提交</ElButton>
                <ElButton type="primary" @click="editDetails()">编辑详细信息</ElButton>
                <ElButton @click="resetForm()">重置</ElButton>
              </ElFormItem>
            </div>
          </ElCol>
        </ElForm>
      </ElRow>
      <!-- 弹窗, 新增 / 修改 -->
      <UserDetailForm v-if="addOrUpdateVisible" ref="userDetailForm" />
    </BasicContainer>
  </div>
</template>

<script>
  import { getDataURL, openWindow } from '@/util'
  import { mapState } from 'vuex'
  import { getStore } from '@/util/store'
  import { isValidateNoneMobile } from '@/util/validate'
  import { editInfo } from '@/api/admin/user'
  import UserDetailForm from '@/module/admin/userinfo/userinfoDialog'
  import { getToken } from '@/util/auth'
  import { transparentImage } from '@/const'
  import { rule } from '@/util/validateRules'

  export default {
    components: { UserDetailForm },
    data() {
      const validatePhone = (rule, value, callback) => {
        if (isValidateNoneMobile(value)[0]) {
          callback(new Error(isValidateNoneMobile(value)[1]))
        } else {
          callback()
        }
      }
      const validatePass = (rule, value, callback) => {
        if (this.ruleForm.password !== '') {
          if (value !== this.ruleForm.newpassword1) {
            callback(new Error('两次输入密码不一致!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        avatarUrl: transparentImage,
        headers: {
          Authorization: `Bearer ${getToken()}`
        },
        ruleForm: {
          username: '',
          password: '',
          newpassword1: '',
          newpassword2: '',
          avatar: '',
          phone: '',
          nickname: '',
          name: '',
          email: ''
        },
        rules: {
          phone: [
            {
              required: false,
              validator: validatePhone,
              trigger: 'blur'
            }
          ],
          password: [
            {
              required: true,
              min: 6,
              message: '原密码不少于6位',
              trigger: 'blur'
            }
          ],
          newpassword1: [
            {
              required: false,
              min: 6,
              message: '新密码不少于6位',
              trigger: 'blur'
            }
          ],
          newpassword2: [
            {
              required: false,
              validator: validatePass,
              trigger: 'blur'
            },
            {
              required: false,
              validator: rule.validatorPassword,
              trigger: 'blur'
            }
          ]
        },
        addOrUpdateVisible: false
      }
    },
    computed: {
      ...mapState('user', { userInfo: state => state.sysUser })
    },
    created() {
      this.resetForm()
    },
    methods: {
      async submitForm() {
        try {
          await this.$refs.ruleForm.validate()

          await editInfo(this.ruleForm)
          this.$notify.success('修改成功')
          // 修改后注销当前token,重新登录
          await this.$store.dispatch('user/handleLogout')
          location.reload()
        } catch (e) {}
      },
      async resetForm() {
        this.ruleForm.password = undefined
        this.ruleForm.newpassword1 = undefined
        this.ruleForm.newpassword2 = undefined
        this.ruleForm.username = this.userInfo.username
        this.ruleForm.phone = this.userInfo.phone
        this.ruleForm.avatar = this.userInfo.avatar
        this.ruleForm.nickname = this.userInfo.nickname
        this.ruleForm.name = this.userInfo.name
        this.ruleForm.email = this.userInfo.email
        this.avatarUrl = await getDataURL(this.userInfo.avatar)
        // 判断是否选择了租户ID
        const TENANT_ID = getStore('tenantId')
        if (TENANT_ID) {
          this.headers['TENANT-ID'] = TENANT_ID // 租户ID
        }
      },
      handleAvatarSuccess(res, file) {
        this.avatarUrl = URL.createObjectURL(file.raw)
        this.ruleForm.avatar = res.data.url
      },
      async editDetails() {
        this.addOrUpdateVisible = true
        await this.$nextTick()
        await this.$refs.userDetailForm.init(this.ruleForm.userinfoId, this.userInfo.userId, this.userInfo.username)
      },
      handleClick(thirdpart) {
        let appid, clientId, url
        const redirectUri = encodeURIComponent(`${window.location.origin}/#/authredirect`)
        if (thirdpart === 'wechat') {
          appid = 'wxd1678d3f83b1d83a'
          url = `https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&redirect_uri=${redirectUri}&state=WX-BIND&response_type=code&scope=snsapi_login#wechat_redirect`
        } else if (thirdpart === 'tencent') {
          clientId = '101322838'
          url = `https://graph.qq.com/oauth2.0/authorize?response_type=code&state=QQ-BIND&client_id=${clientId}&redirect_uri=${redirectUri}`
        } else if (thirdpart === 'gitee') {
          clientId = '235ce26bbc59565b82c989aa3a407ce844cf59a7c5e0f9caa9bb3bf32cee5952'
          url = `https://gitee.com/oauth/authorize?response_type=code&state=GITEE-BIND&client_id=${clientId}&redirect_uri=${redirectUri}`
        } else if (thirdpart === 'osc') {
          clientId = 'neIIqlwGsjsfsA6uxNqD'
          url = `https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=${clientId}&state=OSC-BIND&redirect_uri=${redirectUri}`
        }
        openWindow(url, thirdpart, 540, 540)
      }
    }
  }
</script>

<style lang="scss">
  @import '@/assets/styles/info';
</style>
